package utils;

import java.math.BigInteger;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import play.db.jpa.JPA;
import utils.LogUtil;

public class CommonUtils {
	
	public enum TableIndex{
		orders,
		insurance,
		customer,
		ticketsell
	}
	
	/**
	 * 获得某表的ID
	 * 根据LocalID取得ID，独立事务，每调用一次自动加1
	 * @param localID 地区编号
	 * @TableIndex 表的索引号
	 * @return 返回一个ID
	 * @throws Exception 
	 */
	public static long GetPKID(TableIndex tableIndex) throws Exception 
	{
		long PKID=0,id=0;
		long bit=10000000000L;
		EntityManager em = null;
		try
		{
			//先增加再取值
			//JPA.em().createNativeQuery("Update PKidentity Set PKID=PKID+1 where TableIndex=1").executeUpdate();
//			if (JPA.em().getTransaction().isActive()==false)
//				JPA.em().getTransaction().begin();
			em = JPA.newEntityManager();
			em.getTransaction().begin();
			Query query = em.createNativeQuery("Update idbuild Set currentid=currentid+1 where tablename=?1");
			query.setParameter(1, tableIndex.name());
			int result = query.executeUpdate(); //影响的记录数
			
			if (result>0)
			{
				//int i=1/0;
				Query querySelect = em.createNativeQuery("Select currentid from idbuild Where tablename=?1");
				querySelect.setParameter(1, tableIndex.name());
				String rss = querySelect.getSingleResult().toString();
				BigInteger rs= new BigInteger(rss); 
				id=rs.longValue();
				PKID=(100+tableIndex.ordinal());
				PKID=PKID*bit+id;
				em.getTransaction().commit();
				//JPA.em().joinTransaction()
				return Long.valueOf(PKID);
			}
			else
			{
				em.getTransaction().rollback();
				//throw new play.exceptions.UnexpectedException(Messages.get("ALERT.REGISTER.GET_ID_ERROR"));
			}
		}catch (Exception e) {
			em.getTransaction().rollback();
			LogUtil.logerror(null, "获得ID号出现错误", e);
			throw e;
		}finally{
			if(em.getTransaction().isActive()){
				em.getTransaction().commit();
			}
			if(em!=null){
				if(em.isOpen()){
					em.close();
				}
			}
		}
		return 0l;
	}

}
